/***************************************************************************
 * 文件名：CodeGenerator
 * 功能：
 * 说明：
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/15 9:11:52
 * 创建人：葛浩
 * 邮箱： 2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace BuiltInTools
{
	public class CodeGeneratorUtil
	{
		/// <summary>
		/// 模板文件路径
		/// </summary>
		private const string c_TemplateDir = "TemplateFile";

		/// <summary>
		/// 获取表名模型列表
		/// </summary>
		/// <param name="connectString"></param>
		/// <returns></returns>
		public static List<TableModel> GetTableModels(string connectString)
		{
			using (SqlDBContext context = new SqlDBContext(connectString))
			{
				return context.GetTableNames();
			}
		}

		/// <summary>
		/// 获取表的字段模型列表
		/// </summary>
		/// <param name="connectString"></param>
		/// <returns></returns>
		public static List<ColumnInfoModel> GetTableInfoModels(string tableName, string connectString)
		{
			using (SqlDBContext context = new SqlDBContext(connectString))
			{
				return context.GetTableColumns(tableName);
			}
		}

		/// <summary>
		/// 获取所有数据库
		/// </summary>
		/// <param name="connectString"></param>
		/// <returns></returns>
		public static List<string> GetAllDataBases(string connectString)
		{
			using (SqlDBContext context = new SqlDBContext(connectString))
			{
				return context.GetAllDataBase();
			}
		}

		/// <summary>
		/// 测试连接
		/// </summary>
		/// <param name="connectString"></param>
		public static void TestConnectHost(string connectString)
		{
			using (SqlDBContext context = new SqlDBContext(connectString))
			{

			}
		}

		/// <summary>
		///  代码生成
		/// </summary>
		/// <param name="templateModels"></param>
		/// <param name="templateFilePath"></param>
		/// <returns></returns>
		/// <exception cref="Exception"></exception>
		public static string GeneratorTemlplateCode(TemplateModel model, string templateFileDir)
		{
			if (model == null)
			{
				return string.Empty;
			}

			//若文件目录为空，则重新赋值
			if (string.IsNullOrEmpty(templateFileDir))
			{
				return string.Empty;
			}

			//创建NVelocity引擎的实例对象
			VelocityEngine velocity = new VelocityEngine();

			//初始化该实例对象
			ExtendedProperties props = new ExtendedProperties();
			props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
			props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateFileDir);
			props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
			props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
			velocity.Init(props);

			//合并模板
			StringWriter writer = new StringWriter();

			if (!File.Exists(Path.Combine(templateFileDir, model.TemplateFileName)))
			{
				return string.Empty;
			}

			//从文件中读取模板
			Template temp = velocity.GetTemplate(model.TemplateFileName);
			VelocityContext vltContext = new VelocityContext();
			vltContext.Put("SimplePropertyModels", model.SimplePropertyModels);
			vltContext.Put("BusinessPropertyModels", model.BusinessPropertyModels);
			vltContext.Put("FilterPropertyModels", model.FilterPropertyModels);
			vltContext.Put("AllPropertyModels", model.AllPropertyModels);

			//合并模板
			temp.Merge(vltContext, writer);

			return writer.ToString();
		}

		/// <summary>
		/// 获取主机连接配置
		/// </summary>
		/// <param name="filePath"></param>
		/// <returns></returns>
		public static List<DatabaseConnection> GetDataBaseConfiguration(string filePath)
		{
			if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
			{
				return null;
			}

			XmlDocument document = new XmlDocument();
			document.Load(filePath);
			if (document == null)
			{
				return null;
			}

			XmlNode singleNode = document.SelectSingleNode("//connectionStrings");
			if (singleNode == null)
			{
				return null;
			}

			List<DatabaseConnection> connections = new List<DatabaseConnection>();

			foreach (XmlNode node in singleNode.ChildNodes)
			{
				if (node == null) { continue; }

				string name = node.Attributes["name"].Value;
				string connectString = node.Attributes["connectionString"].Value;

				if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(connectString))
				{
					continue;
				}

				//添加至返回列表
				connections.Add(new DatabaseConnection
				{
					HostConnectName = name,
					ConnectString = connectString
				});
			}

			return connections;
		}
	}
}
